package com.pro.xwt.common.interceptor;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.mysql.jdbc.StringUtils;
import com.pro.xwt.common.model.BToken;
import com.pro.xwt.common.service.BEmployeeService;
import com.pro.xwt.common.service.BTokenService;
import com.pro.xwt.common.utils.ThreeDESUtil;


public class LoginInterceptor implements HandlerInterceptor{
	
	@Autowired
	BTokenService tokenService;
	@Autowired
	BEmployeeService bEmployeeService;
	
	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
		
	}

	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
			throws Exception {
		
	}

	public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2) throws Exception {
		//1、请求到登录页面 放行  
	    if(arg0.getServletPath().startsWith("/admin/login")) {  
	        return true;  
	    }  
		//读请求头
		String authToken = arg0.getHeader("Xwt-Request-Token");
		System.out.println(authToken);
		//请求头为空时查询cookies
		if (authToken==null||authToken.equals("")) {
			arg1.getWriter().write("Token为空");
			return false;
		}
		//3、如果用户已经登录 放行    
		BToken bToken = new BToken();
		bToken.setAuthToken(authToken);
		String userInfos=decodeToken(authToken);
		bToken.setUserId(userInfos);
		bToken.setExpireTime(new Date());
		//bToken.setIp(Common.toIpAddr(arg0));
		BToken bt = tokenService.select(bToken);
		System.out.println(bt);
		//过期校验
		if (bt==null) {
			//arg1.getWriter().write("<script type='text/javascript'> window.top.location='../front/html/front.html'</script>");
			arg1.getWriter().write("Token失效");
			return false;
		}else{
			arg0.setAttribute("user", bEmployeeService.findById(bToken.getUserId()));
			System.out.println(bEmployeeService.findById(bToken.getUserId()));
			return true;
		}
		
	    //2、TODO 比如退出、首页等页面无需登录，即此处要放行 允许游客的请求  
	          
	    
	   /* if(arg0.getSession().getAttribute("admin") != null) {  
	    	//更好的实现方式的使用cookie  
	        return true;  
	    } */ 
	          
	    //4、非法请求 即这些请求需要登录后才能访问  
	    //重定向到登录页面  
	  /*  arg1.getWriter().write("<script type='text/javascript'> window.top.location='../admin/login'</script>");*/
	    
	   /* return false;  */
	}
	
	private static String TAG="LoginInterceptor";
	//加密解密 秘钥   和门户之间
	private static final String SEED="d$*16?.ghb#!&bke";
	//分隔符
	public static final String SPLIT_CHAR="|";
	/**
	 * 解码请求应用信息
	 * @param token (appId,cdnToken,responseTimeStamp)
	 * @param decodeType
	 */
	public static String decodeToken(String token){
		System.out.println(TAG+": decode(token:"+token+") start");
		String userInfoStr=null;
		System.out.println(TAG+": AES decode start");
		userInfoStr=new ThreeDESUtil().getDecString(token, SEED);
		System.out.println(TAG+": AES decode end");
		System.out.println(TAG+": decode() end");
		String userInfos=null;
		if(!StringUtils.isNullOrEmpty(userInfoStr)){
			int i =userInfoStr.indexOf(SPLIT_CHAR);
			userInfos = userInfoStr.substring(0,i);
		}
		return userInfos;
	}

}
